package org.example.interceptor;

import java.util.Map;

import org.example.constant.JwtClaimsConstant;
import org.example.properties.JwtProperties;
import org.example.utils.JwtUtil;
import org.example.utils.ThreadLocalUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    private final JwtProperties jwtProperties;

    private final RedisTemplate redisTemplate;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            // 当前拦截到的不是动态方法，直接放行
            return true;
        }
        // 令牌头部验证
        String token = request.getHeader(jwtProperties.getUserTokenName());
        // 判断token
        try {
            // 从redis中获取token
            ValueOperations<String, String> operations = redisTemplate.opsForValue();
            String redisToken = operations.get(JwtClaimsConstant.TOKEN);
            if (redisToken == null) {// token失效
                throw new RuntimeException("请先登录！");
            }
            // 解析并验证token,如果解析失败，则抛出异常
            Map<String, Object> claims = JwtUtil.paresToken(jwtProperties.getUserSecretKey(), token);
            // 把claims中的用户信息放入ThreadLocal中
            ThreadLocalUtil.set(claims);
            return true;// 通过验证
        } catch (Exception e) {
            response.setStatus(401);
            // response.sendError(401,"请先登录！");
            return false;// 未通过验证
        }
    }

    // 请求处理完毕后拦截器
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // 清除ThreadLocal中的用户信息
        ThreadLocalUtil.remove();
    }
}
